<template>
	<view class="detail">
		<view class="container">
			<view v-if="!loadState"><u-skeleton rows="3" title loading></u-skeleton></view>
			<view v-else>
				<view class="title">{{detailObj.title}}</view>

				<view class="userinfo">
					<view class="avatar">
						<image :src="giveAvatar(detailObj)" mode="aspectFill"></image>
					</view>
					<view class="text">
						<view class="name">
							{{giveName(detailObj)}}
						</view>
						<view class="small">
							<uni-dateformat :date="detailObj.publish_date"
								format="yyyy年MM月dd hh:mm:ss"></uni-dateformat>
							<text>-发布于{{detailObj.province}}</text>
						</view>
					</view>
				</view>

				<view class="content">
					<u-parse :content="detailObj.content" :tagStyle="tagStyle"></u-parse>
				</view>

				<view class="like">
					<!-- 点赞量 -->
					<view class="btn" :class="detailObj.isLike ? 'active' : ''" @click="clickLike">
						<text class="iconfont icon-good-fill"></text>
						<text v-if="detailObj.like_count">{{detailObj.like_count}}</text>
					</view>
					<!-- 点赞用户头像 -->
					<view class="users">
						<template v-for="item in likeUserArr">
							<image v-if="item.user_id[0].avatar_file" :src="giveAvatar(item)" mode="aspectFill">
							</image>
						</template>
					</view>
					<!-- 浏览量 -->
					<view class="text"><text class="num">{{detailObj.view_count}}</text>人看过</view>
				</view>

			</view>
		</view>

		<view class="comment">
			<view style="padding-bottom:50rpx" v-if="!commentList.length && noComment">
				<u-empty mode="comment"
					icon="https://mp-8cdd1d45-191b-4b0c-bd17-fc78f6e9d354.cdn.bspapp.com/comment.png">
				</u-empty>
			</view>

			<view class="content" v-if="commentList.length">
				<view class="item" v-for="item in commentList">
					<!-- :childState="!(item.totalReply ? true : false)" -->
					<CommentItem :item="item" @removeEnv="PremoveEnv" @click.native="openReplyItem(item)">
					</CommentItem>
				</view>
			</view>

			<view v-if="commentList.length" style="padding-bottom: 120rpx;">
				<uni-load-more :status="uniLoad"></uni-load-more>
			</view>
		</view>

		<CommentFrame :commentObj="commentObj" @commentEnv="PcommentEnv"></CommentFrame>

		<CommentPopup ref="commentPopup"></CommentPopup>

		<view class="totop" v-show="showToTopBtn" @click="totop">
			<u-icon name="arrow-up" color="#2979ff" size="28"></u-icon>
		</view>
	</view>
</template>

<script>
	import pageJson from "@/pages.json"
	import {
		giveName,
		giveAvatar,
		likeFun
	} from "@/utils/tools.js"
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	const db = uniCloud.database();
	const dbCmd = db.command;
	const utilsObj = uniCloud.importObject("CloudFishCircle-utilsObj", {
		customUI: true
	});
	export default {
		data() {
			return {
				uniLoad: "more",
				limitNum: 3,
				showToTopBtn: false,
				artid: 0,
				loadState: false,
				tagStyle: {
					p: "line-height:1.7em;font-size:18px;padding-bottom:10rpx",
					img: "margin:10rpx 0"
				},
				detailObj: null,
				likeUserArr: [],
				commentList: [],
				noComment: false,
				commentObj: {
					article_id: "",
					comment_type: 0
				},
				placeholder: "评论点什么吧",
			};
		},
		onLoad(e) {
			// console.log(e);
			if (!e.id) {
				this.errFun();
				return;
			}
			this.artid = e.id;
			this.commentObj.article_id = e.id
			this.getData();
			this.readUpdate()
			this.getLikeUser();
			this.getComment(this.commentList.length, this.limitNum)
		},
		onShow() {
			uni.$on('uni-id-pages-login-success', () => {
				this.getLikeState()
			})
		},
		// 页面滚动
		onPageScroll(e) {
			// toTopBtn_inThrottle = false
			this.throttleFun(this.changeShowToTopBtnState, 'toTopBtn_inThrottle', 80)(e.scrollTop, 'showToTopBtn')
		},
		// 页面触底
		onReachBottom() {
			// console.log('触底了。。。');
			// reachBottom_inThrottle = false;
			this.throttleFun(this.onReachBottomFun, 'reachBottom_inThrottle', 2000)(this.commentList.length, this.limitNum)
		},
		methods: {
			giveName,
			giveAvatar,
			// 节流
			throttleFun(func, inThrottled, limit) {
				return (...args) => {
					if (!this[`${inThrottled}`]) {
						this[`${inThrottled}`] = true;
						func.apply(this, args)
						setTimeout(() => (this[`${inThrottled}`] = false), limit);
					}
				}
			},
			// 改变ToTopBtn显示状态
			changeShowToTopBtnState(scrollTopVal, ToTopBtnState) {
				if (scrollTopVal >= 300) {
					this[`${ToTopBtnState}`] = true
				} else {
					this[`${ToTopBtnState}`] = false
				}
			},
			onReachBottomFun(skipNum, limitNum) {
				this.uniLoad = 'loading'
				this.getComment(skipNum, limitNum).then((res) => {
					if (res == 0) {
						this.uniLoad = 'nomore'
					}else{
						this.uniLoad = 'more'
					}
				})

			},
			// 返回顶部
			totop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 150
				});
			},
			//查看评论回复
			openReplyItem(item) {
				// console.log(item);
				this.$refs.commentPopup.open(item);
			},
			//删除评论的回调
			PremoveEnv(e) {
				let index = this.commentList.findIndex(item => {
					return item._id == e.id
				})
				this.commentList.splice(index, 1)
			},
			//评论成功后的回调
			PcommentEnv(e) {
				// console.log(e);
				this.commentList.unshift({
					...this.commentObj,
					...e,
					user_id: [store.userInfo]
				})
			},
			//获取评论列表
			async getComment(skipNum, limitNum) {
				let commentTemp = db.collection("cloud_fishCircle-comments")
					.where(`article_id == "${this.artid}" && comment_type==0`).orderBy("comment_date desc").skip(
						skipNum).limit(limitNum).getTemp();
				let userTemp = db.collection("uni-id-users").field("_id,username,nickname,avatar_file").getTemp()

				let res = await db.collection(commentTemp, userTemp).get()

				let idArr = res.result.data.map(item => {
					return item._id
				})

				let replyArr = await db.collection("cloud_fishCircle-comments").where({
						reply_comment_id: db.command.in(idArr)
					}).groupBy('reply_comment_id')
					.groupField('count(*) as totalReply').get();

				console.log("res", res);
				// console.log("idArr", idArr);
				// console.log("replyArr", replyArr);

				res.result.data.forEach(item => {
					let index = replyArr.result.data.findIndex(find => {
						return find.reply_comment_id == item._id
					})
					if (index > -1) item.totalReply = replyArr.result.data[index].totalReply
				})

				if (res.result.data == 0) this.noComment = true

				// this.commentList = res.result.data
				let oldArr = this.commentList
				this.commentList = [...oldArr, ...res.result.data]
				return res.result.data.length
			},
			//获取数据
			getData() {
				let artTemp = db.collection("cloud_fishCircle-article").where(`_id=="${this.artid}"`).getTemp()
				let userTemp = db.collection("uni-id-users").field("_id,username,nickname,avatar_file").getTemp()
				let likeTemp = db.collection("cloud_fishCircle-like").where(
					`article_id=="${this.artid}" && user_id==$cloudEnv_uid`).getTemp();

				let tempArr = [artTemp, userTemp];
				if (store.hasLogin) tempArr.push(likeTemp)

				db.collection(...tempArr).get({
					getOne: true
				}).then(res => {
					// console.log(res);
					if (!res.result.data) {
						this.errFun();
						return;
					}
					let isLike = false;
					if (store.hasLogin) isLike = res.result.data._id["cloud_fishCircle-like"].length ? true :
						false;
					res.result.data.isLike = isLike;
					this.detailObj = res.result.data
					uni.setNavigationBarTitle({
						title: this.detailObj.title
					})
					this.loadState = true
					uni.setStorageSync('breakUrl', 1)
				}).catch(err => {
					// console.log(err);
					this.errFun();
				})
			},
			//获取点赞状态
			getLikeState() {
				let artTemp = db.collection("cloud_fishCircle-article").where(`_id=="${this.artid}"`).getTemp()
				let likeTemp = db.collection("cloud_fishCircle-like").where(
					`article_id=="${this.artid}" && user_id==$cloudEnv_uid`).getTemp();
				let tempArr = [artTemp, likeTemp];
				db.collection(...tempArr).get({
					getOne: true
				}).then(res => {
					// console.log(res);
					if (!res.result.data) {
						this.errFun();
						return;
					}
					let isLike = res.result.data._id["cloud_fishCircle-like"].length ? true : false;
					res.result.data.isLike = isLike;
					this.detailObj = res.result.data
				}).catch(err => {
					this.errFun();
				})
			},
			//获取部分点赞的用户
			getLikeUser() {
				let likeTemp = db.collection("cloud_fishCircle-like").where(`article_id == "${this.artid}"`).getTemp()
				let userTemp = db.collection("uni-id-users").field("_id,avatar_file").getTemp()
				db.collection(likeTemp, userTemp).orderBy("publish_date", "desc").limit(5).get().then(res => {
					// console.log(res);
					res.result.data = res.result.data.reverse()
					this.likeUserArr = res.result.data
				})
			},
			//点赞操作
			async clickLike() {
				if (!store.hasLogin) {
					uni.showModal({
						title: "登录后才可进行后续操作",
						success: res => {
							if (res.confirm) {
								uni.navigateTo({
									url: "/" + pageJson.uniIdRouter.loginPage
								})
							}
						}
					})
					return;
				}

				let time = Date.now();
				if (time - this.likeTime < 2000) {
					uni.showToast({
						title: "操作太频繁，请稍后...",
						icon: "none"
					})
					return;
				}
				this.detailObj.isLike ? this.detailObj.like_count-- : this.detailObj.like_count++;
				this.detailObj.isLike = !this.detailObj.isLike
				this.likeTime = time;
				//调用点赞方法
				likeFun(this.artid);

			},
			//修改阅读量
			readUpdate() {
				utilsObj.operation("cloud_fishCircle-article", "view_count", this.artid, 1).then(res => {
					// console.log(res);
				})
			},
			//错误的处理
			errFun() {
				uni.showToast({
					title: "参数有误",
					icon: "none"
				})
				setTimeout(() => {
					uni.reLaunch({
						url: "/pages/index/index"
					})
				}, 1000)
			},
		}
	}
</script>

<style lang="scss">
	.detail {
		width: 100vw;
		background: #f8f8f8;
		min-height: calc(100vh - var(--window-top));

		.totop {
			position: sticky;
			float: right;
			right: 20rpx;
			bottom: 400rpx;
			padding: 10rpx;
			background-color: #fff;
			border: 1rpx solid #999;
			border-radius: 10rpx;
			z-index: 20;
		}

		.container {
			padding: 30rpx;
			background: #fff;

			.title {
				font-size: 46rpx;
				color: #333;
				line-height: 1.4em;
				font-weight: 600;
			}

			.userinfo {
				padding: 20rpx 0 50rpx;
				display: flex;
				align-items: center;

				.avatar {
					width: 60rpx;
					height: 60rpx;
					padding-right: 15rpx;

					image {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}

				.text {
					font-size: 28rpx;
					color: #555;

					.small {
						font-size: 20rpx;
						color: #999;
					}
				}
			}

			.content {}

			.like {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 80rpx 50rpx 50rpx;

				.btn {
					width: 260rpx;
					height: 120rpx;
					background: #e4e4e4;
					border-radius: 100rpx;
					color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					font-size: 28rpx;
					font-weight: 600;

					.iconfont {
						font-size: 50rpx;
					}

					&.active {
						background: #0199FE;
					}
				}

				.text {
					font-size: 26rpx;
					color: #666;

					.num {
						color: #0199FE
					}

					.spot {
						padding: 0 10rpx;
					}
				}

				.users {
					display: flex;
					justify-content: center;
					padding: 30rpx 0;

					image {
						width: 60rpx;
						height: 60rpx;
						border-radius: 50%;
						border: 3px solid #fff;
						margin-left: -20rpx;
					}
				}
			}

		}

		.comment {
			padding: 30rpx;
			padding-bottom: 120rpx;

			.item {
				padding: 10rpx 0;
			}
		}
	}
</style>